package com.handinfo.android.game;

import java.io.DataInputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PointF;
import android.view.MotionEvent;

import com.handinfo.android.DWGameManager;
import com.handinfo.android.core.graphics.DWFont;
import com.handinfo.android.core.graphics.DWGraphics;
import com.handinfo.android.core.graphics.DWScreen;
import com.handinfo.android.core.net.BaseConnection;
import com.handinfo.android.core.net.GameProtocol;
import com.handinfo.android.core.object.AbstractGameHandler;
import com.handinfo.android.core.object.Scene;
import com.handinfo.android.core.resource.DWSerializableFactory;
import com.handinfo.android.core.resource.ResHead;
import com.handinfo.android.core.resource.ResourceManager;
import com.handinfo.android.game.particle.ParticleConstants;
import com.handinfo.android.game.skill.SkillResult;
import com.handinfo.android.ui.UIWindows;
import com.handinfo.android.ui.window.UIHook;
import com.handinfo.android.ui.window.UIMap;
import com.handinfo.android.uicontrols.controls.DWImageBox;
import com.handinfo.android.utils.Tools;

public class Loading extends AbstractGameHandler
{
	public static final int SCENE_PROCESS = 5;
	private Bitmap m_tiao_1 = null;
	private Bitmap m_tiao_2 = null;
	private Bitmap[] m_tou = null;
	private Bitmap m_beijing = null;
	private int m_tiao1_x = 0;
	private int m_tiao1_y = 0;
	private int m_tiao2_x = 0;
	private int m_tiao2_y = 0;

	public Loading()
	{
	}

	public boolean recvMessage(int type, DataInputStream dis) throws Exception
	{
		int order = BaseConnection.s_perseOrderID;
		try {
			Tools.debugPrintln("Loading 接收到指令号 : " + order);
			DWGameManager.getInstance().getSendMessage()
					.unlockNetwork(GameMessage.锁_默认);
			switch (order) {
				case GameProtocol.SC_USER_INFORMATION:
					Tools.debugPrintln("读取角色基础信息");
					recvRoleInformation(dis);
					break;
				case GameProtocol.CS_COMBAT_SKILL_LIST:
					Tools.debugPrintln("读取角色技能信息");
					DWGameManager.getInstance().m_role.initCombatSkill(dis);
					break;
				case GameProtocol.SC_TEAM_TEAMLEADERCHANGE:
					Tools.debugPrintln("读取角色队伍信息");
					DWGameManager.getInstance().m_role.recvTeamLeaderChange(dis);
					break;
				case GameProtocol.SC_COLUMN_COMMAND:
					Tools.debugPrintln("读取角色道具信息");
					DWGameManager.getInstance().m_role.recvColumnCommand(dis);
					break;
				case GameProtocol.CS_TASK_ROLE_LIST:
					Tools.debugPrintln("读取角色任务");
					UIWindows.getInstance().m_renwu.recvRoleTaskList(dis);
					break;
				case GameProtocol.CS_TASK_ACCEPTABLYTASKLIST:
					Tools.debugPrintln("读取角色可接任务");
					UIWindows.getInstance().m_renwu.recvRoleacceptablyTaskList(dis);
					break;
				case GameProtocol.SC_CHONGWU_KUOBEIBAO:
					Tools.debugPrintln("recv 宠物扩背包");
					UIWindows.getInstance().m_pet.recvPetBagNum(dis);
					break;
				case GameProtocol.SC_TIANMING_BAG:
					Tools.debugPrintln("recv 天命背包数据");
					UIWindows.getInstance().m_jiming.recvTianMingBug(dis);
					break;
				case GameProtocol.SC_TIANMING_MONEY:
					Tools.debugPrintln("recv k开启天命拜神花费");
					UIWindows.getInstance().m_jiming.recvTianMingJiBaiMoney(dis);
					break;
				case GameProtocol.SC_LOGIN_ROLE_INFO_END:
					Tools.debugPrintln("读取角色信息完毕");
					s_progress++;
					break;
				case GameProtocol.SC_SCENE_INFORMATION:
					Tools.debugPrintln("读取场景信息");
					recvSceneInformation(dis);
					s_progress++;
//					s_progress = 7;//谢亮修改
					break;
				case GameProtocol.SC_REQUEST_ROLE_MAILS:
					Tools.debugPrintln("读取角色邮件");
					DWGameManager.getInstance().m_role.recvRequestRoleMails(dis);
					break;
				case GameProtocol.SC_SCENE_MAP:
					UIMap.recvSceneMap(dis);
					break;
				case GameProtocol.SC_INIT_ACTIVE_COMBAT_SKILL:
					Tools.debugPrintln("读取角色激活技能列表");
					DWGameManager.getInstance().m_role.initShortcut(dis);
					break;
				case GameProtocol.SC_MARRIAGE_MESSAGE:
					Tools.debugPrintln("婚姻信息" + GameProtocol.SC_MARRIAGE_MESSAGE);
					DWGameManager.getInstance().m_role.recvMarriageMessage(dis);
					break;
				case GameProtocol.SC_EQUIPMENT_OPEN:
					Tools.debugPrintln("revc接收锻造属性" + GameProtocol.SC_EQUIPMENT_OPEN);
					UIWindows.getInstance().m_tiangong.recvEquipmentOpen(dis);
					break;
				default:
					Tools.debugPrintln("revc，没有此指定处理："+order);
					break;
			}
		}
		catch (Exception ex) {
			Tools.debug(ex);
			return false;
		}
		return true;
	}

	/**
	 * 读取场景信息
	 * 
	 * @param dis
	 * @throws IOException
	 */
	private void recvSceneInformation(DataInputStream dis) throws IOException
	{
		UIHook.closeHook();
		DWGameManager.getInstance().m_stage = dis.readUTF();// 地图ID
		DWGameManager.getInstance().m_map_name = dis.readUTF();// 地图名
		DWGameManager.getInstance().m_role.deactivate();
		DWGameManager.getInstance().m_role_x = dis.readShort();
		DWGameManager.getInstance().m_role_y = dis.readShort();
		DWGameManager.getInstance().m_scene_type = dis.readByte();
		DWGameManager.getInstance().m_scene_pk = dis.readByte();
		Tools.debugPrintln("地图ID : " + DWGameManager.getInstance().m_stage);
		Tools.debugPrintln("坐标 x : "
				+ DWGameManager.getInstance().m_role.m_posX);
		Tools.debugPrintln("坐标 y : "
				+ DWGameManager.getInstance().m_role.m_posY);
		Tools.debugPrintln("地图类型 : " + DWGameManager.getInstance().m_scene_type);
		Tools.debugPrintln("地图专属是否PK : "
				+ DWGameManager.getInstance().m_scene_pk);

		// byte dir = dis.readByte();// 人物方向

		DWGameManager.getInstance().m_role.setAction(Role.ACTION_STAND
				* Role.DIRECT_NUM, true);
		DWGameManager.getInstance().m_sceneResList.clean();
		if (DWGameManager.getInstance().m_role.m_refsResHead == null) {

		}
		int resNum = dis.readShort();
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < resNum; i++) {
			int type = dis.readByte();
			String url = dis.readUTF();
			int version = dis.readInt();
			buffer.delete(0, buffer.length());
			switch (type) {
				case DWSerializableFactory.RESOURCE_TYPE_ANIM:
					buffer.append(DWSerializableFactory.DIR_ANIM);
					buffer.append(url);
					buffer.append(DWSerializableFactory.EXTENSION_ANIM);
					break;
				case DWSerializableFactory.RESOURCE_TYPE_BG:
					buffer.append(DWSerializableFactory.DIR_BG);
					buffer.append(url);
					buffer.append(DWSerializableFactory.EXTENSION_BG);
					break;
				case DWSerializableFactory.RESOURCE_TYPE_PNG:
					buffer.append(DWSerializableFactory.DIR_IMG);
					buffer.append(url);
					buffer.append(DWSerializableFactory.EXTENSION_IMG);
					break;
				case DWSerializableFactory.RESOURCE_TYPE_SCENE:
					buffer.append(DWSerializableFactory.DIR_SCENE);
					buffer.append(url);
					buffer.append(DWSerializableFactory.EXTENSION_SCENE);
					break;
			}
			url = buffer.toString();
			ResHead resHead = new ResHead(type, url, version);
			DWGameManager.getInstance().m_sceneResList.put(resHead);
			if (type == DWSerializableFactory.RESOURCE_TYPE_SCENE) {
				DWGameManager.getInstance().mSceneResHead = resHead;
			}
		}

		ResourceManager.getInstance().updateResource(
				DWGameManager.getInstance().m_resourceDynamic,
				DWGameManager.getInstance().m_sceneResList);
		m_scene = (Scene) ResourceManager.getInstance().loadResource(
				DWGameManager.getInstance().m_resourceDynamic,
				DWGameManager.getInstance().mSceneResHead);

		int size = dis.readByte();
		if (m_scene != null) {
			String[] names = new String[size];
			short[] xs = new short[size];
			short[] ys = new short[size];
			int[] distance = new int[size];
			byte[] isIn = new byte[size];
			for (int i = 0; i < size; i++) {
				names[i] = dis.readUTF();
				xs[i] = dis.readShort();
				ys[i] = dis.readShort();
				distance[i] = dis.readInt();
			}
			m_scene.m_dname = names;
			m_scene.m_dx = xs;
			m_scene.m_dy = ys;
			m_scene.m_distance = distance;
			m_scene.m_isIn = isIn;
		}
		Tools.debugPrintln("场景信息读取完毕!");

	}

	private Scene m_scene = null;

	public void paint(DWGraphics g)
	{
		if (m_counter != 0) {
			drawLoadingBar(g, m_counter);
		}

	}

	public int m_counter = 0;// loading计时器

	public void drawLoadingBar(DWGraphics g, int counter)
	{
		int color = 0xFFF3BA0C;
		if (counter < 0 || counter > 100)
			return;

		g.setClip(0, 0, DWGameManager.Screen_Width, DWGameManager.Screen_Height);
		g.drawBitmap(m_beijing, 0, 0, DWGameManager.Screen_Width,
				DWGameManager.Screen_Height, Tools.LEFT_TOP);

		// int y = DWGameManager.Screen_Height -
		// m_str_tip.length*g.getFontHeight()>>1;

		for (int i = 0; i < m_str_tip.length; i++) {
			g.drawShadowString(m_str_tip[i], Color.BLACK, color,
					DWGameManager.Screen_Width / 2,
					m_tiao1_y - g.getFontHeight() * (m_str_tip.length - 1 - i)
							- 10, Tools.HCENTER_BOTTOM);
		}

		g.drawShadowString(DWFont.getFont(22), "(" + counter + "%)",
				Color.BLACK, color, DWGameManager.Screen_Width / 2,
				m_tiao1_y + 35, Tools.HCENTER_TOP);
		g.drawBitmap(m_tiao_1, m_tiao1_x, m_tiao1_y, Tools.LEFT_TOP);
		int pw = counter * m_tiao_2.getWidth() / 100;
		g.setClip(m_tiao2_x, m_tiao2_y, pw, m_tiao_2.getHeight());
		g.drawBitmap(m_tiao_2, m_tiao2_x, m_tiao2_y, Tools.LEFT_TOP);

		g.setClip(m_tiao2_x, m_tiao2_y, pw + 50, m_tiao_2.getHeight());
		g.drawBitmap(m_tou[m_timer % m_tou.length], m_tiao2_x + pw, m_tiao2_y,
				Tools.HCENTER_TOP);
	}

	public static int s_progress = 0;// 进度
	private int m_timer = 0;
	private static boolean m_jiazai = false;

	private boolean m_jinru2 = true;
	private boolean m_jinru = true;

	public void logic()
	{

		switch (s_progress) {
			case 0:
				Login.writePastInto();
				s_progress++;
				break;
			case 1:
				if (m_jinru) {
					setFrameInterval(100);
					new Thread(new Runnable() {
						public void run()
						{
							UIWindows.getInstance().init();
							UIWindows.getInstance().init2();
							UIWindows.getInstance().init3();
							UIWindows.getInstance().init4();
							UIWindows.getInstance().initend();
							// 光效
							GameEffect.initStaticResource();
							// npc
							Npc.initStaticResource();
							// 伤害数字
							SkillResult.initStaticResource();
							ParticleConstants.initResource();
							m_jinru = false;
							s_progress = 3;
							setFrameInterval(50);
						}
					}).start();
				}
				s_progress++;
				break;
			case 2:
				if (m_counter < 80)
					m_counter++;
				break;
			case 3:
				DWGameManager
						.getInstance()
						.getSendMessage()
						.sendUserInformation(
								DWGameManager.getInstance().m_role.m_gameId);
				DWGameManager.getInstance().getSendMessage().sendRequestRoleMails();
				s_progress++;
				break;
			case 4:
				if (m_counter < 90)
					m_counter++;
				break;
			case 5:
				DWGameManager
						.getInstance()
						.getSendMessage()
						.sendSceneInformation(
								DWGameManager.getInstance().m_role.m_gameId);
				s_progress++;
				break;
			case 6:
				if (m_counter < 99)
					m_counter++;
				break;
			case 7:
				if (m_counter < 100) {
//					if (m_counter < 100) {
					m_counter++;
				}
				else {
					m_scene.m_id = DWGameManager.getInstance().m_stage;
					m_scene.m_name = DWGameManager.getInstance().m_map_name;
					m_scene.m_sceneType = DWGameManager.getInstance().m_scene_type;
					DWGameManager.getInstance().setGameHandler(
							m_scene.m_sceneHandler);
					DWGameManager.getInstance().setGameState(DWGameManager.GS_GAME);
					s_progress = -1;
					m_jinru2 = true;
				}
				break;
		}
		if (++m_timer > 1000000) {
			m_timer = 0;
		}

	}

	/**
	 * 读取角色信息
	 * 
	 * @param dis
	 * @throws IOException
	 */
	private void recvRoleInformation(DataInputStream dis) throws IOException
	{
		Role role = DWGameManager.getInstance().m_role;

		role.m_name = dis.readUTF();
		Tools.debugPrintln("名字 : " + role.m_name);

		role.m_sex = dis.readByte();
		Tools.debugPrintln("性别 : " + role.m_sex);

		role.m_vocation = dis.readByte();
		Tools.debugPrintln("职业 : " + role.m_vocation);

		role.m_faction = dis.readByte();
		Tools.debugPrintln("阵营 : " + role.m_faction);

		role.m_lv = dis.readInt();
		Tools.debugPrintln("等级 : " + role.m_lv);

		role.m_vip_lv = dis.readByte();
		Tools.debugPrintln("VIP等级 : " + role.m_vip_lv);

		role.m_status = dis.readByte();
		Tools.debugPrintln("状态 : " + role.m_status);

		role.m_action = dis.readInt();
		Tools.debugPrintln("行为 : " + role.m_action);

		role.m_hp = dis.readInt();
		Tools.debugPrintln("当前HP : " + role.m_hp);

		role.m_mp = dis.readInt();
		Tools.debugPrintln("当前MP : " + role.m_mp);

		role.m_exp = (int) dis.readLong();
		Tools.debugPrintln("当前经验 : " + role.m_exp);

		role.m_maxExp = (int) dis.readLong();
		Tools.debugPrintln("当前总经验 : " + role.m_maxExp);

		role.m_gold = dis.readLong();
		Tools.debugPrintln("游戏金币 : " + role.m_gold);

		role.m_zhangong = dis.readLong();
		Tools.debugPrintln("游戏战功 : " + role.m_zhangong);

		role.m_rmb = dis.readLong();
		Tools.debugPrintln("游戏元宝 : " + role.m_rmb);

		role.m_banggong = dis.readLong();
		Tools.debugPrintln("游戏帮贡 : " + role.m_banggong);

		role.m_xiuwei = dis.readLong();
		Tools.debugPrintln("游戏修为 : " + role.m_xiuwei);

		role.m_jinghun = dis.readLong();
		Tools.debugPrintln("游戏精魂 : " + role.m_jinghun);

		role.m_rongyu = dis.readLong();
		Tools.debugPrintln("游戏荣誉 : " + role.m_rongyu);

		role.m_zhanli = dis.readLong();
		Tools.debugPrintln("角色战力 : " + role.m_zhanli);
		UIWindows.getInstance().m_zhanli.m_zhanli_loading = role.m_zhanli;//获取角色登陆时的战力值 mujianchen

		role.m_position = dis.readByte();
		Tools.debugPrintln("家族职位 : " + role.m_position);

		role.m_teamID = dis.readLong();
		Tools.debugPrintln("队伍ID : " + role.m_teamID);

		role.m_jinglizhi_zonggong = dis.readInt();
		Tools.debugPrintln("总共精力值: " + role.m_jinglizhi_zonggong);

		role.m_jinglizhi_shengyu = dis.readInt();
		Tools.debugPrintln("剩余精力值: " + role.m_jinglizhi_shengyu);

		// 其他属性
		int size = dis.readByte();
		role.m_attributes = new int[size];
		for (int i = 0; i < size; i++) {
			role.m_attributes[i] = dis.readInt();
		}

		role.m_hpMax = role.getAttr(Attribute.MAX_HP);
		Tools.debugPrintln("当前HP_MAX: " + role.m_hp);

		role.m_mpMax = role.getAttr(Attribute.MAX_MP);
		Tools.debugPrintln("当前MP_MAX: " + role.m_mp);

		role.m_needSendPath = true;
		if (UIWindows.getInstance().m_baitan != null) {
			UIWindows.getInstance().m_baitan.SELL_TYPE = false;
		}

		if (UIWindows.getInstance().m_soul != null) {
			UIWindows.getInstance().m_soul.release();
		}

		// 师徒限制等级
		role.m_shitu_tudilv = dis.readInt();
		role.m_shitu_laoshi = dis.readInt();
		role.m_shitu_guanxi = dis.readUTF();
		
		role.m_jinbi_num01 = dis.readInt();
		role.m_jinbi_num02 = dis.readInt();
		role.m_yuanbao_numMin01 = dis.readInt();
		role.m_yuanbao_numMin02 = dis.readInt();
		role.m_yuanbao_numMax01 = dis.readInt();
		role.m_yuanbao_numMax02 = dis.readInt();
		// int animCount = 3;
		// role.m_anims = new Animation[animCount];
		// role.m_refsResHead = new ResHead[animCount];
		role.initActor();
	}

	public boolean doClick(PointF point)
	{
		return false;
	}

	public boolean doDoubleClick(PointF point)
	{
		return false;
	}

	public boolean doLongPress(PointF point)
	{
		return false;
	}

	public boolean doScroll(PointF start, PointF end, float distanceX,
			float distanceY)
	{
		return false;
	}

	public boolean doFling(PointF start, PointF end, float velocityX,
			float velocityY)
	{
		return false;
	}

	public boolean doDrag(PointF start, PointF end, float velocityX,
			float velocityY)
	{
		return false;
	}

	public boolean doDown(PointF point)
	{
		return false;
	}

	public boolean doLongScroll(PointF start, PointF end, float distanceX,
			float distanceY)
	{
		return false;
	}

	public void init()
	{
		setFrameInterval(30);
		m_tiao_1 = UIWindows.createImage("/img/newui/jinduxia_1.gnp");
		m_tiao_2 = UIWindows.createImage("/img/newui/jindushang_1.gnp");
		m_tou = new Bitmap[3];
		for (int i = 0; i < m_tou.length; i++) {
			m_tou[i] = UIWindows.createImage("/img/newui/jindubiao_" + (i + 1)
					+ ".gnp");
		}
		m_beijing = UIWindows.createImage("/img/newui/denglubjt_1.gnp");
		m_tiao1_x = (DWGameManager.Screen_Width - m_tiao_1.getWidth()) / 2;
		m_tiao1_y = DWGameManager.Screen_Height / 7 * 6;
		m_tiao2_x = m_tiao1_x
				+ (DWGameManager.AdpaterType == DWGameManager.AD_HIGH ? 42 : 32);
		m_tiao2_y = m_tiao1_y
				+ (DWGameManager.AdpaterType == DWGameManager.AD_HIGH ? 17 : 12);

		m_str_tip = Tools.splitString(
				STR_TIPS[Tools.random(STR_TIPS.length - 1)],
				DWGameManager.Screen_Width * 2 / 3, 0, DWFont.getDefaultFont());
	}

	public void quit()
	{
		UIWindows.removeImage("/img/newui/jinduxia_1.gnp");
		UIWindows.removeImage("/img/newui/jindushang_1.gnp");
		UIWindows.removeImage("/img/newui/denglubjt_1.gnp");
		m_tiao_1 = null;
		m_tiao_2 = null;
		if (m_tou != null) {
			for (int i = 0; i < m_tou.length; i++) {
				m_tou[i] = null;
				UIWindows.removeImage("/img/newui/jindubiao_" + (i + 1)
						+ ".gnp");
			}
			m_tou = null;
		}

	}

	public boolean onTouch(MotionEvent event, PointF point)
	{
		// TODO Auto-generated method stub
		return false;
	}

	private String[] m_str_tip;

	public static final String[] STR_TIPS = {
			"好友可为你的摇钱树浇水，摇钱树每天可以收获一次，可收获到元宝！",
			"进入家族后，只要完成任务及通关副本，即可获得家族贡献值；家族达到升级人数及经验值要求后，就会自动升级。",
			"家族副本每日均可开启，击杀boss可获得大量金钱", "个人竞技场每日均会根据排名颁发奖励，排名越高，奖励越丰厚！",
			"只要参加个人与家族竞技场即可获得战功，积攒一定量战功之后即可炼化内丹",
			"装备灵石和炼化内丹都可以提升你的基础属性，从而增加你的能力", "将你杀死的玩家会自动成为你的“仇敌”",
			"使用金钱拜祭神仙即可获得天命，装备可以极大地提升你的战斗能力",
			"力量可提升物理攻击及防御、智力可提升法术攻击及防御、技巧可提升命中与暴击减免、敏捷可提升闪避及暴击伤害，每个属性都十分有用！",
			"击杀世界boss可获得意想不到的独特装备，世界boss重生时间很长，要注意查看服务器的通知信息",
			"通关副本需要消耗精力值，精力值每天发放100点，还可使用元宝购买额外精力",
			"宠物可以提升你的各项属性或经验值获取，坐骑则可以极大地提升你的行走速度",
			"在“助手”中可以查看每天可以完成的任务，与定时开启的活动",
			"在屏幕空白处长按一段时间，即可触发虚拟摇杆，控制角色移动" };
	// public static final String[] STR_LOADING_INFO = {"正在加载角色信息", "正在加载角色背包"}
}
